/**
 * Copyright 2009 University of  Washington
 * This code is released under the GPL version 3 - with a copy of the license included
 * @author Maya Hao Li
 *
 */
package seedpod.webapp.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import seedpod.exceptions.SeedpodException;
import seedpod.model.NoObjectFoundException;
import seedpod.model.SeedpodDO;
import seedpod.rdb.PMFactory;
import seedpod.rdb.PManager;
import seedpod.util.Util;
import seedpod.webapp.LimsSession;
import seedpod.webapp.Seedpod;
import seedpod.webapp.view.InstanceRenderer;

public class ActionDeleteInstance extends HttpServlet {
	private static final long serialVersionUID = -5550078233869117058L;
	public static final String URL = "actionDeleteInstance";
	private int _oid;
	private PManager _manager;

	public void init() {
		try {
			PMFactory factory = Seedpod.getPersistenceManagerFactory();
			_manager = factory.createManager();
		}
		catch (SeedpodException se) {
			System.err.println( " Cannot find valid Persistence Manager. " + se.getMessage() );
		}
	}

	protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException,
			IOException {
		doPost( request, response );
	}

	protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException,
			IOException {
		String oidStr = (String)request.getParameter( InstanceRenderer.OID );
		_oid = (oidStr != null) ? Integer.decode( oidStr ) : 0;

		LimsSession spSession = LimsSession.getSession( request );

		if ( _manager == null ) {
			spSession.addSessionErrorMsg( "Cannot connect to the database" );
			Util.redirect( "error.jsp", request, response );
		}

		SeedpodDO spDO;
		try {
			spDO = _manager.createObject( _oid );
			if ( spDO.delete() ) {
			spSession.setAttribute( Util.getSeedpodInternalId( spDO ), spDO);
			Util.redirect( "../lims/instance.jsp?oid="+_oid+"&status="+spDO.getState(), request, response );
			} 
			else
			{
				spSession.addSessionErrorMsg( "Failed to delete object with oid " + _oid );
				Util.redirect( "error.jsp", request, response );
			}
		}
		catch (NoObjectFoundException e1) {
			spSession.addSessionErrorMsg( e1.getMessage() );
			Util.redirect( "error.jsp", request, response );
		}
		catch (SeedpodException e) {
			spSession.addSessionErrorMsg( "Failed to delete object with OID " + _oid + ". To view the object: "
					+ "<a href=\"../lims/instance.jsp?oid=" + _oid + "\">click here</a>" );
			Util.redirect( "error.jsp", request, response );
		}

	}

	public static String getUrl( int oid ) {
		return "../lims/" + URL + "?oid=" + oid;
	}

}
